package com.CGFrame.struts.action.categorySet;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;

import com.CGFrame.struts.POJOs.Category;
import com.CGFrame.struts.POJOs.Company;
import com.CGFrame.struts.bean.category.CategoryBean;
import com.CGFrame.struts.bean.company.CompanyBean;
import com.CGFrame.struts.bean.log.LogHistoryBean;

public class CreateAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String name=request.getParameter("categoryname");
		String ename=request.getParameter("categoryename");
		String type=request.getParameter("categorytype");
		
		HttpSession session = request.getSession();
		String companyId = (String)session.getAttribute("CompanyID");
		
		Company c=CompanyBean.getCompanyById(Integer.valueOf(companyId)); 
		
		if(name=="" || ename==""){
			request.setAttribute("catenull", "name or englishname can not be null!");
			request.setAttribute( "categories", c.getCategories() );
			return mapping.findForward("queryCategory");
		}
		
		CategoryBean cb=new CategoryBean();
		List categorys=cb.getCategorys();
		for(Iterator iter=categorys.iterator();iter.hasNext();){
			Category cat=(Category)iter.next();
			if(cat.getCategoryName()==name || cat.getCategoryEnglishName()==ename || cat.getCategoryType()==type){
				request.setAttribute("catedup", "category duplicated!");
				request.setAttribute( "categories", c.getCategories() );
				return mapping.findForward("queryCategory");
			}
		}
		
		
		int resultId = cb.createCategory(companyId, name, ename, type);
		
		LogHistoryBean logBean = new LogHistoryBean();
		String regUserId = (String)request.getSession().getAttribute("RegUserID");
		logBean.saveByReguserId(regUserId, LogHistoryBean.ADD,name+" - "+ename, "Category",resultId );
		
		request.setAttribute( "categories", c.getCategories() );
		return mapping.findForward("queryCategory");
	}
}
